<?php

/**
 * @author PeoneEr
 *  контроллер для гмшопа
 */
require_once "core/application/models/mgmshop/mgmshop.php";
require_once "core/application/classes/isOnlineClass.php";
require_once "core/application/classes/errorClass.php";
require_once "core/application/controllers/cmoney.php";

class GMShop_Controller extends GMShop_Model {

    /**
     *
     * @var static $_instance
     * @var array $_fetch
     * @var string $_race
     * @var string $_type
     * @var string $_cat
     * @var object $_lang
     * @var array $_params
     * @var int $_balance
     * @var int $_newBalance
     * @var int $_id
     * @var int $_itemUniqueId
     * @var aux $_list
     */
    private static $_instance = NULL;
    private $_fetch        = array();
    private $_race            = NULL;
    private $_type            = NULL;
    private $_cat             = NULL;
    public $_lang             = NULL;
    public $_params        = array();
    private $_balance            = 0;
    private $_newBalance         = 0;
    private $_id                 = 0;
    private $_itemUniqueId       = 0;
    private $_list            = NULL;
    private $_price              = 0;

    public static function getInstance() {
        /**
         * Singleton pattern
         */
        if (is_null(self::$_instance)) {
            $class = __CLASS__;
            self::$_instance = new $class();
        }
        return self::$_instance;
    }

    private function switchType($type) {
        /**
         *  определение типа вещи
         */
        switch ($type) {
            case "weapon": $this->_type = "оружие";
                break;
            case "armor": $this->_type = "броня";
                break;
            case "potion": $this->_type = "бутыли";
                break;
            case "other": $this->_type = "разное";
                break;
            case "pets": $this->_type = "петы";
				break;
            default: $this->_type = "не определено";
        }
        return $this->_type;
    }

    private function switchCategory($category) {
        /**
         *  определение категории
         */
        switch ($category) {
            case "weapon": $this->_cat = "оружие";
                break;
            case "armor": $this->_cat = "броня";
                break;
            case "potion": $this->_cat = "бутыли";
                break;
            case "other": $this->_cat = "разное";
                break;
			case "pets": $this->_cat = "петы";
				break;
            default: $this->_cat = "не определено";
        }
        return $this->_cat;
    }

    private function switchRace($race) {
        /**
         *  определение расы
         */
        switch ($race) {
            case elyos: $this->_race = "Элийцы";
                break;
            case asmodians: $this->_race = "Асмодиане";
                break;
            case all: $this->_race = "Все";
                break;
            default: $this->_race = "не определено";
        }
        return $this->_race;
    }

    private function catchPlayerNameAndID() {
        /**
         *  в массиве ник чара на отправку и идентификатор предмета
         * @return array $params
         */
        $params = array(
            'playerName' => $_POST['char'],
            'id' => $_POST['what'],
            'countOfBuy' => $_POST['countOfBuy']
        );
        return $params;
    }

    public function deleteItem() {
        /**
         *  метод для админки
         * удаление предмета с продажи
         */
        $this->_lang = $this->getLanguage();
        try {
            $this->deleteRecord($this->catchId());
            $this->echoSuccess($this->_lang->language['success']);
            unset($this->_lang);
        } catch (Exception $e) {
            echo $e->getFile();
            echo $e->getLine();
            error::getInstance($this->_lang->language['defaultError']);
            unset($this->_lang);
        }
    }

    private function catchId() {
        /**
         * 	возвращает значение $_GET['id']
         * @return int $_GET['id']
         */
        return $_GET['id'];
    }

    private function catchAddItem() {
        /**
         * 	метод для админки
         * содержит инфу для добавления предмета в продажу
         * @return array $params
         */
        $params = array(
            'itemName' => $_POST['itemName'],
            'itemId' => $_POST['itemId'],
            'price' => $_POST['price'],
            'race' => $_POST['race'],
            'type' => $_POST['type'],
            'level' => $_POST['level']
        );
        return $params;
    }

    public function insertNewItem() {
        /**
         * 	админский метод
         * 		добавление итема в продажу
         */
        $this->_params = $this->catchAddItem();
        $this->_lang = $this->getLanguage();
        try {
            foreach ($this->_params as $key => $val) {
                if ($key == 'level') {
                    if ($val < 0 || $val > 55) {
                        $this->echoError("Уровень должен быть в интервале от 0 до 55");
                    }
                }
            }
        } catch (Exception $e) {
            echo $e->getFile();
            echo $e->getLine();
        }
        if ($this->issetItem($this->_params['itemId'])) {
            $this->echoError("Предмет с таким ID уже зарегистрирован в продаже");
        }
        try {
            $this->insertNewRecord($this->_params['price'], $this->_params['type'], $this->_params['level'], $this->_params['race'], $this->_params['itemName'], $this->_params['itemId'], $this->_params['type']);
            $this->echoSuccess($this->_lang->language['success']);
            unset($this->_params, $this->_lang);
        } catch (Exception $e) {
            error::getInstance($this->_lang->language['defaultError']);
            unset($this->_params, $this->_lang);
        }
    }

    public function buyAndSend() {
        /**
         * покупка предмета и его отправка експресс почтой (нужен тест)
         */
        $this->_lang = $this->getLanguage();
        $this->_params = $this->catchPlayerNameAndID();

        if ($this->_params['playerName'] == "Выберите персонажа") {
            $this->echoError("Не был выбран персонаж");
        }

        if (round($this->_params['countOfBuy']) < 1) {
            $this->_params['countOfBuy'] = 1;
        }

        if (!$this->issetRecord($this->_params['id'])) {
            $this->echoError($this->_lang->language['defaultError']);
            unset($this->_id, $this->_params, $this->_lang, $this->_itemUniqueId);
        }
        try {
            foreach ($this->_params as $key => $val) {
                if (empty($val)) {
                    $this->echoError($this->_lang->language['emptyValue']);
                    unset($key, $this->_params);
                }
            }
        } catch (Exception $e) {
            echo $e->getFile();
            echo $e->getLine();
        }
        /**
         * определение цены n кол-ва предметов
         */
        $this->_price = $this->getPrice($this->_params['id']) * round($this->_params['countOfBuy']);
        /**
         * баланс покупающего
         */
        $this->_balance = Cmoney::getInstance()->showMoney();
        if ($this->_balance < $this->_price) {
            $this->echoError($this->_lang->language['noEnoughBalance']);
        }
        /**
         * баланс после покупки
         */
        $this->_newBalance = $this->_balance - $this->_price;

        if (isOnline::getInstance()->online($this->_params['playerName'])) {
            $this->echoError("Персонаж в игре");
        }
        /**
         * 	присвоение случайных значений к максимуму
         */
        $this->_id = $this->getMaxMailId() + rand(1,20);
        $this->_itemUniqueId = $this->getMaxItemUniqueId() + rand(1,20);
        if ($this->_id == $this->_itemUniqueId || $this->_id - 1 == $this->_itemUniqueId - 1) {
            $this->_id += 2;
            //$this->_itemUniqueId += 2;
        }
        try {
            //обновление баланса 
            Cmoney::getInstance()->updateMoney($this->_newBalance);
            try {
                /**
                 * 	новый предмет в инвентарь
                 * @param int itemUiqueId
                 * @param int itemId
                 * @param int playerId
                 * @param int count
                 */
                $this->addItem($this->_itemUniqueId, $this->getItemId($this->_params['id']), $this->getPlayerID($this->_params['playerName']), $this->_params['countOfBuy']);
                try {
                    //отправка сообщения
                    $this->sendExpressMessage($this->_id, $this->getPlayerID($this->_params['playerName']), "Support", $this->getItemName($this->_params['id']), "Покупка предмета", $this->_itemUniqueId);
                    //вывод сообщения
                    $this->echoSuccess("
                        Вы успешно приобрели предмет <b>" . $this->getItemName($this->_params['id']) . "</b> в кол-ве " . $this->_params['countOfBuy'] . ". 
                    <br />
                    Предмет отправлен экспресс почтой персонажу <b>" . $this->_params['playerName'] . "</b>. С Вашего счета списано <b>" . $this->getPrice($this->_params['id']) . "</b> Y.E. 
                    <br />
                    Спасибо за покупку!");
                    //запись в лог
                    $this->insertNewLog($this->getPlayerID($this->_params['playerName']), $this->getItemName($this->_params['id']), $this->getItemId($this->_params['id']), 'success');
                    unset($this->_id, $this->_params, $this->_lang, $this->_itemUniqueId);
                } catch (Exception $e) {
                    echo $e->getMessage();
                    error::getInstance($this->_lang->language['defaultError']);
                    unset($this->_id, $this->_params, $this->_lang, $this->_itemUniqueId);
                }
            } catch (Exception $e) {
                $this->insertNewLog($this->getPlayerID($this->_params['playerName']), $this->getItemName($this->_params['id']), $this->getItemId($this->_params['id']), 'error');
                echo $e->getMessage();
                error::getInstance($this->_lang->language['defaultError']);
                unset($this->_id, $this->_params, $this->_lang, $this->_itemUniqueId);
            }
        } catch (Exception $e) {
            $this->insertNewLog($this->getPlayerID($this->_params['playerName']), $this->getItemName($this->_params['id']), $this->getItemId($this->_params['id']), 'error');
            echo $e->getMessage();
            error::getInstance($this->_lang->language['defaultError']);
            unset($this->_id, $this->_params, $this->_lang, $this->_itemUniqueId);
        }
    }

    public function players() {
        /**
         * вывод списка чаров на аккаунте
         */
        $this->_list = $this->getChars();
        $this->_lang = $this->getLanguage();
        try {
            while ($this->_fetch = mysql_fetch_assoc($this->_list)) {
                echo "<option value='" . $this->_fetch['name'] . "'>" . $this->_fetch['name'] . "</option>";
            } unset($this->_fetch, $this->_language, $this->_list);
        } catch (Exception $e) {
            $e->getLine();
            $e->getFile();
            error::getInstance($this->_lang->language['defaultError']);
            unset($this->_fetch, $this->_language, $this->_list);
        }
    }

    public function showOneRecord($id) {
        /**
         * одна запись в гмшопе, которую можно уже купить
         * @param $id
         */
        $this->_list = $this->getOneItem($id);
        $this->_lang = $this->getLanguage();
        if (!$this->issetRecord($id)) {
            $this->echoError($this->_lang->language['defaultError']);
        }
        try {
            while ($this->_fetch = mysql_fetch_assoc($this->_list)) {
                $this->_type = $this->switchType($this->_fetch['type']);
                $this->_cat = $this->switchCategory($this->_fetch['category']);
                $this->_race = $this->switchRace($this->_fetch['race']);
                printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><tr>", $this->_fetch['itemName'], $this->_fetch['price'], $this->_race, $this->_type, $this->_fetch['level'], $this->_cat);
            }
            unset($this->_fetch, $this->_race, $this->_cat, $this->_type, $this->_lang, $this->_list);
        } catch (Exception $e) {
            echo $e->getLine();
            echo $e->getFile();
            error::getInstance($this->_lang->language['defaultError']);
            unset($this->_fetch, $this->_language, $this->_list, $this->_type, $this->_cat, $this->_race);
        }
    }

    public function randomItems() {
        /**
         * (non-phpdoc)
         * @see mgmshop.php var $_limit сколько предметов будет выводиться
         */
        $this->_list = $this->randomRecords();
        $this->_lang = $this->getLanguage();
        try {
            while ($this->_fetch = mysql_fetch_assoc($this->_list)) {
                $this->_type = $this->switchType($this->_fetch['type']);
                $this->_cat = $this->switchCategory($this->_fetch['category']);
                $this->_race = $this->switchRace($this->_fetch['race']);
                printf("<tr><td><a href='index?services&do=buy&what=%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><tr>", $this->_fetch['id'], $this->_fetch['itemName'], $this->_fetch['price'], $this->_race, $this->_type, $this->_fetch['level'], $this->_cat);
            }
            unset($this->_fetch, $this->_language, $this->_list, $this->_type, $this->_cat, $this->_race);
        } catch (Exception $e) {
            echo $e->getFile();
            echo $e->getLine();
            error::getInstance($this->_lang->language['defaultError']);
            unset($this->_fetch, $this->_language, $this->_list, $this->_type, $this->_cat, $this->_race);
        }
    }

    public function viewAll() {
        /**
         * админский метод
         * вывод всех предметов в продаже
         */
        $this->_lang = $this->getLanguage();
        $this->_list = $this->getFullList();
        try {
            while ($this->_fetch = mysql_fetch_assoc($this->_list)) {
                $this->_type = $this->switchType($this->_fetch['type']);
                $this->_cat = $this->switchCategory($this->_fetch['category']);
                $this->_race = $this->switchRace($this->_fetch['race']);
                printf("<tr><td><a href='index?adm&settings&action=gameshop&subaction=gmshop_delete_item&id=%s'><img src='content/images/del_ban.gif'></img></a></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><tr>", $this->_fetch['id'], $this->_fetch['itemName'], $this->_fetch['price'], $this->_race, $this->_type, $this->_fetch['level'], $this->_cat);
            }
            unset($this->_fetch, $this->_language, $this->_list, $this->_type, $this->_cat, $this->_race);
        } catch (Exception $e) {
            echo $e->getFile();
            echo $e->getLine();
            error::getInstance($this->_lang->language['defaultError']);
            unset($this->_fetch, $this->_language, $this->_list, $this->_type, $this->_cat, $this->_race);
        }
    }

    public function showCategory($category) {
        /**
         * 	вывод предметов по категории
         * @param string $category
         */
        $this->_lang = $this->getLanguage();
        switch ($category) {
            case 'all':
                $this->_list = $this->getFullList();
                try {
                    while ($this->_fetch = mysql_fetch_assoc($this->_list)) {
                        $this->_type = $this->switchType($this->_fetch['type']);
                        $this->_cat = $this->switchCategory($this->_fetch['category']);
                        $this->_race = $this->switchRace($this->_fetch['race']);
                        printf("<tr><td><a href='index?services&do=buy&what=%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><tr>", $this->_fetch['id'], $this->_fetch['itemName'], $this->_fetch['price'], $this->_race, $this->_type, $this->_fetch['level'], $this->_cat);
                    }
                    unset($this->_fetch, $this->_race, $this->_cat, $this->_type, $this->language);
                } catch (Exception $e) {
                    echo $e->getFile();
                    echo $e->getLine();
                    error::getInstance($this->_lang->language['defaultError']);
                    unset($this->_fetch, $this->_race, $this->_cat, $this->_type, $this->language, $this->_list);
                }
                break;
            case 'weapon':
            case 'armor':
            case 'potion':
            case 'other':
            case "pets":
                try {
                    $this->_fetch = mysql_fetch_assoc($this->getListByCategory($category));
                    $this->_list = $this->getListByCategory($category);
                    if (empty($this->_fetch))
                        echo ("<b>Категория <span style='color: red'>пуста</span></b>");
                    while ($this->_fetch = mysql_fetch_assoc($this->_list)) {
                        $this->_type = $this->switchType($this->_fetch['type']);
                        $this->_cat = $this->switchCategory($this->_fetch['category']);
                        $this->_race = $this->switchRace($this->_fetch['race']);
                        printf("<tr><td><a href='index?services&do=buy&what=%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><tr>", $this->_fetch['id'], $this->_fetch['itemName'], $this->_fetch['price'], $this->_race, $this->_type, $this->_fetch['level'], $this->_cat);
                    }
                    unset($this->_fetch, $this->_race, $this->_cat, $this->_type, $this->_lang, $this->_list);
                } catch (Exception $e) {
                    echo $e->getFile();
                    echo $e->getLine();
                    error::getInstance($this->_lang->language['defaultError']);
                    unset($this->_fetch, $this->_race, $this->_cat, $this->_type, $this->_lang);
                }
                break;
                break;
                break;
                break;
            default: $this->echoError("Нет такой категории.");
                break;
        }
    }

}

?>
